package encheres.dao.impl;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import encheres.dao.HibernateUtil;
import encheres.dao.IClientDAO;
import encheres.dao.entities.Client;

/**
 * Implémente les méthode DAO des objets Client.
 * @author Nicolas
 *
 */
public class ClientDAOImpl implements IClientDAO {

	/**
     * {@inheritDoc}
     */
    public void creerClient(final Client nouveauClient) throws HibernateException {
        Session session = null;
        Transaction tx = null;
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            tx = session.beginTransaction();
            session.save(nouveauClient);
            tx.commit();
        } catch (HibernateException e) {
            if(tx != null){
                tx.rollback();
            }
            throw e;
        } finally {
            session.close();
        }
    }

    /**
     * {@inheritDoc}
     */
    public Client findClient(final String login, final String mdp) throws HibernateException {
        Session session = null;
        Transaction tx = null;
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            tx = session.beginTransaction();
            String requete = "From Client c Where c.loginClient='"+login+"' and c.mdpClient='"+mdp+"'";
            Client client = (Client)session.createQuery(requete).uniqueResult();
            
            return client;
        } catch (HibernateException e) {
            if(tx != null){
                tx.rollback();
            }
            throw e;
        } finally {
            session.close();
        }
    }
    
    /**
     * {@inheritDoc}
     */
    public Client findClient(final int idClient) throws HibernateException {
    	Session session = null;
    	Transaction tx = null;
    	try {
    		session = HibernateUtil.getSessionFactory().openSession();
    		tx = session.beginTransaction();
    		String requete = "From Client c where c.idClient="+idClient;
    		Client client = (Client) session.createQuery(requete).uniqueResult();
    		
    		return client;
    	} catch (HibernateException e) {
    		if(tx != null){
                tx.rollback();
            }
            throw e;
		} finally {
			session.close();
		}
    }

}
